<script setup lang="ts">
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox, ElOption, ElSelect } from 'element-plus'
import Inspecting from './Inspecting.vue'
import declartion from './declartion.vue'
import type { InspectForm } from './page'
import { statusType } from './page'
import { usePage } from '@/utils/commonHook'
import { useDeclareStates } from '@/utils/dataHook'
import dataQueryApi from '@/api/modules/data.query'
import useUserStore from '@/store/modules/user'
import { AccountType } from '@/api/modules/types/user'
import { DeclareState } from '@/api/modules/types/data.query'
import { ModelType } from '@/types/common'

const userStore = useUserStore()
const route = useRoute()
const tableData = ref<any[]>([])
const { page, pageNumChange, pageSizeChange } = usePage(getTableData)
const AffiliatedObjType = userStore.userInfo.AffiliatedObjType

interface TimeRangeType {
  startTime: string
  endTime: string
}
const inspectingRef = ref()
const declartionRef = ref()

const timeRange = reactive<TimeRangeType>({
  startTime: '',
  endTime: '',
})

const searchData = reactive({
  stateIDs: [],
  entName: '',
})

const { startTime, endTime } = route.query || {}
if (startTime) {
  timeRange.startTime = startTime as string
}
if (endTime) {
  timeRange.endTime = endTime as string
}

const tiemValue = computed({
  set: (values) => {
    const realValues = values || []
    timeRange.startTime = realValues[0]
    timeRange.endTime = realValues[1]
  },
  get: () => {
    return [timeRange.startTime, timeRange.endTime]
  },
})

const declareStates = useDeclareStates()

const loading = ref(false)
async function getTableData() {
  loading.value = true
  const res = await dataQueryApi.GetOverhaulDeclare({
    startTime: timeRange.startTime,
    endTime: timeRange.endTime,
    declareIDs: [],
    stateIDs: searchData.stateIDs,
    entNames: [searchData.entName],
    pageSize: page.PageSize,
    pageNum: page.PageNum,
  })
  loading.value = false
  const { Items, RecordsetCount } = res
  tableData.value = Items || []
  page.RecordsetCount = RecordsetCount
}

function search() {
  page.PageNum = 1
  getTableData()
}

getTableData()

function approve(row: any) {
  inspectingRef.value?.open({
    data: row,
  })
}

function addDeclear() {
  declartionRef.value?.open({
    type: ModelType.add,
  })
}
function addDeclearAgein(row: any) {
  declartionRef.value?.open({
    type: ModelType.add,
    data: row,
  })
}

function approveSubmit(data: { data: InspectForm, isPass: boolean }) {
  ElMessageBox.confirm(`确认提交${data.isPass ? '通过' : '驳回'}审核吗？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const api = data.isPass ? dataQueryApi.OverhaulDeclareOrgPass : dataQueryApi.OverhaulDeclareOrgBack
    api(data.data).then(() => {
      ElMessage({
        type: 'success',
        message: '提交成功',
      })
      inspectingRef.value?.close()
      getTableData()
    })
  })
}

function declearSubmit(formData: any) {
  const { DeclareID, ReuseObjID, StartTime, EndTime, ReportContent, ReportName, ReportTel } = formData
  const data = {
    declareID: DeclareID || null,
    reuseObjID: ReuseObjID,
    startTime: StartTime,
    endTime: EndTime,
    reportContent: ReportContent,
    reportName: ReportName,
    reportTel: ReportTel,
  }
  dataQueryApi.OverhaulDeclareEnt(data).then((res) => {
    declartionRef.value.upload(res)
    declartionRef.value?.close()
    ElMessage({
      type: 'success',
      message: '提交成功',
    })
  })
}
</script>

<template>
  <div>
    <PageHeader>
      <template #content>
        <ElForm label-width="100">
          <ElRow>
            <ElCol v-if="!userStore.isEnterpris" :span="6">
              <ElFormItem label="企业名称">
                <ElInput v-model="searchData.entName" clearable placeholder="请输入" />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="日期">
                <ElDatePicker v-model="tiemValue" clearable value-format="YYYYMMDD" type="daterange" />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="申报状态">
                <ElSelect v-model="searchData.stateIDs" clearable multiple placeholder="请选择申报状态">
                  <ElOption v-for="item in declareStates" :key="item.ID" :label="item.Name" :value="item.ID" />
                </ElSelect>
              </ElFormItem>
            </ElCol>
            <ElCol :span="6" :push="userStore.isEnterpris ? 6 : 0" class="flex flex-justify-end">
              <ElButton v-if="userStore.isEnterpris" type="primary" @click="addDeclear">
                新增检修申报
              </ElButton>
              <ElButton type="primary" @click="search">
                查询
              </ElButton>
            </ElCol>
          </ElRow>
        </ElForm>
      </template>
    </PageHeader>
    <PageMain>
      <div v-auto-height="85">
        <vxe-table border height="100%" :data="tableData" :loading="loading" :row-config="{ isCurrent: true }">
          <VxeColumn type="seq" title="序号" width="80" />
          <VxeColumn field="ReuseName" title="治理设施" min-width="150" show-overflow />
          <VxeColumn field="EntName" title="企业名称" min-width="220" show-overflow />
          <VxeColumn field="ProduceName" title="检修期间" min-width="300">
            <template #default="{ row }">
              {{ dayjs(row.StartTime).format('YYYY-MM-DD HH:mm') }} 至 {{ dayjs(row.EndTime).format('YYYY-MM-DD HH:mm')
              }}
            </template>
          </VxeColumn>
          <VxeColumn field="ReportName" title="申报人" width="150" />
          <VxeColumn field="ReportTel" title="申报人联系方式" width="200" />
          <VxeColumn field="ReportTime" title="申报时间" width="200" />
          <VxeColumn field="DeclareStateName" title="申报状态" width="200">
            <template #default="{ row }">
              <el-tag :type="statusType(row.DeclareStateID)">
                {{ row.DeclareStateName }}
              </el-tag>
            </template>
          </VxeColumn>
          <VxeColumn title="操作" width="180" fixed="right">
            <template #default="{ row }">
              <el-button
                v-if="AffiliatedObjType === AccountType.EnvOrg && row.DeclareStateID === DeclareState.Inspecting"
                type="primary" link @click="approve(row)"
              >
                审批
              </el-button>
              <el-button
                v-if="AffiliatedObjType === AccountType.Enterpris && row.DeclareStateID === DeclareState.DeclareFail"
                type="primary" link @click="addDeclearAgein(row)"
              >
                再次申报
              </el-button>
            </template>
          </VxeColumn>
        </vxe-table>
      </div>
      <ElPagination
        class="mt-4" :page-size="page.PageSize" :total="page.RecordsetCount" :current-page="page.PageNum"
        layout="total, sizes, prev, pager, next, jumper" :page-sizes="[20, 50, 100]" @current-change="pageNumChange"
        @size-change="pageSizeChange"
      />
      <Inspecting ref="inspectingRef" @submit="approveSubmit" />
      <declartion ref="declartionRef" @submit="declearSubmit" />
    </PageMain>
  </div>
</template>
